const router = require('koa-router')()
const fs = require('fs')
const path = require('path')
const execFile = require("child_process").execFile;

// 读取modules.config.json（所有配置的json数据）并发送
router.get('/init/read_modules', async (ctx, next) => {
  let fileUrl = path.join(__dirname, '../modules.config.json')
  let data = fs.readFileSync(fileUrl)
  ctx.body = data
})

// 接收client的已选模块
router.post('/init/write_modules', async (ctx, next) => {
  let data = JSON.stringify(ctx.request.body)
  let fileUrl = path.join(__dirname, '../modules.deploy.json')
  fs.writeFileSync(fileUrl, data)
  let dist = path.join(__dirname, '../public/main/dist/js/')
  execFile(
    "node",
    ["unpack.js"],
    { cwd: dist },
    (error, stdout, stderr) => {
      if (error) {
        throw error;
      }
      console.log(stdout);
    }
  );
  ctx.body = {
    code: 1
  }
})
// 发送modules.deploy.json
router.get('/init/load_modules', async (ctx, next) => {
  let fileUrl = path.join(__dirname, '../modules.deploy.json')
  let data = fs.readFileSync(fileUrl)
  ctx.body = data
})

router.get('/home', async (ctx, next) => {
  let navgatio_html = path.join(__dirname, '../public/main/navagation.html')
  let data = fs.readFileSync(navgatio_html)
  ctx.response.type = 'html'
  ctx.response.body = data
})

// 启动成功的进程写入deploy文件，添加状态start为true
router.get('/init/launch', async (ctx, next) => {
  let fileUrl = path.join(__dirname, '../modules.deploy.json')
  let fileData = JSON.parse(fs.readFileSync(fileUrl))
  let data = {
    newest: '',
    complete: true
  }
  fileData.map((item) => {
    if (!item.base) {
      if (item.newest === true) {
        data.newest = item.name
      }
      if (!item.start) {
        data.complete = false
      }
    }
  })
  ctx.response.body = data
})



module.exports = router
